package com.example.coder_voucher.repository;

import com.example.coder_voucher.entity.User;
import com.example.coder_voucher.entity.UserVoucher;
import com.example.coder_voucher.entity.Voucher;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;

import java.util.List;
import java.util.Optional;

@Repository
public interface UserVoucherRepository extends JpaRepository<UserVoucher, Long> {
    
    /**
     * Find all vouchers claimed by a user
     */
    List<UserVoucher> findByUserOrderByClaimedAtDesc(User user);
    
    /**
     * Find all users who claimed a specific voucher
     */
    List<UserVoucher> findByVoucherOrderByClaimedAtDesc(Voucher voucher);
    
    /**
     * Find specific user-voucher claim
     */
    Optional<UserVoucher> findByUserAndVoucher(User user, Voucher voucher);
    
    /**
     * Check if user has already claimed a specific voucher
     */
    boolean existsByUserAndVoucherAndStatus(User user, Voucher voucher, UserVoucher.ClaimStatus status);
    
    /**
     * Find user vouchers by status
     */
    List<UserVoucher> findByStatus(UserVoucher.ClaimStatus status);
    
    /**
     * Find user vouchers that can be rolled back
     */
    @Query("SELECT uv FROM UserVoucher uv WHERE uv.user = :user AND uv.status = 'CLAIMED' AND uv.usedAt IS NULL")
    List<UserVoucher> findRollbackableVouchersByUser(@Param("user") User user);
    
    /**
     * Count claimed vouchers for a specific voucher
     */
    @Query("SELECT COUNT(uv) FROM UserVoucher uv WHERE uv.voucher = :voucher AND uv.status IN ('CLAIMED', 'USED')")
    Long countClaimedVouchers(@Param("voucher") Voucher voucher);
    
    /**
     * Find user vouchers by user and status
     */
    List<UserVoucher> findByUserAndStatus(User user, UserVoucher.ClaimStatus status);
}